<template>
  <div
      class="p-4 h-full flex flex-col relative neo-card neo-border">
    <!-- 组件角落装饰 -->
    <div class="absolute top-4 left-4 w-[0.5px] h-8 pointer-events-none">
      <div class="w-full h-full bg-gradient-to-b from-transparent to-blue-400/70"></div>
    </div>
    <div class="absolute top-4 right-4 w-[0.5px] h-8 pointer-events-none">
      <div class="w-full h-full bg-gradient-to-b from-transparent to-blue-400/70"></div>
    </div>
    <div class="absolute bottom-4 left-4 w-1.5 h-1.5 bg-blue-400/50 pointer-events-none"></div>
    <div class="absolute bottom-4 right-4 w-1.5 h-1.5 bg-blue-400/50 pointer-events-none"></div>
    <h2 class="text-lg font-semibold text-center mb-3 relative z-10 title-neo">工单数量曲线</h2>
    <!-- 切换按钮容器 -->
    <div class="flex gap-1 mb-2 self-start relative z-10">
      <button
          class="px-3 py-1.5 text-xs font-medium rounded-lg transition-all duration-300"
          :class="{
          'bg-blue-600 text-white shadow-[0_0_8px_rgba(59,130,246,0.5)]': currentPeriod === 'today',
          'bg-white/5 text-blue-200 hover:bg-white/10 border border-white/10': currentPeriod !== 'today'
        }"
          @click="currentPeriod = 'today'"
      >
        日曲线
      </button>
      <button
          class="px-3 py-1.5 text-xs font-medium rounded-lg transition-all duration-300"
          :class="{
          'bg-blue-600 text-white shadow-[0_0_8px_rgba(59,130,246,0.5)]': currentPeriod === 'month',
          'bg-white/5 text-blue-200 hover:bg-white/10 border border-white/10': currentPeriod !== 'month'
        }"
          @click="currentPeriod = 'month'"
      >
        月曲线
      </button>
    </div>
    <div ref="chart" class="w-full h-64"></div>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount, watch, nextTick} from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'

const chart = ref(null)
let chartInstance = null
const currentPeriod = ref('today')
const loading = ref(true)
const error = ref(null)
const dailyData = ref({xAxis: [], series: []})
const monthlyData = ref({xAxis: [], series: []})
let refreshInterval = null // 存储定时器ID

// 获取日曲线数据
const fetchDailyData = async () => {
  try {
    const res = await axios.get('/api/Notice/GetDailyTicketTrend')
    if (res.data.isSuccess) {
      const data = res.data.data

      // 构建 xAxis（格式如 "00:00", "01:00", ..., "23:00"）
      const xAxis = data.this.map(item => {
        const hour = Number(item.time).toString().padStart(2, '0')
        return `${hour}:00`
      })

      // 构建 series 数据 - 日视图显示"今日"和"昨日"
      const today = data.this.map(item => Number(item.count) || 0)
      const yesterday = data.last.map(item => Number(item.count) || 0)

      dailyData.value = {
        xAxis: xAxis,
        series: [
          {name: '今日', data: today, type: 'line'},
          {name: '昨日', data: yesterday, type: 'line'}
        ]
      }
    } else {
      throw new Error(res.data.msg || '获取日曲线数据失败')
    }
  } catch (err) {
    error.value = '获取日曲线数据失败'
    console.error('日数据错误:', err)
  }
}

// 获取月曲线数据
const fetchMonthlyData = async () => {
  try {
    const res = await axios.get('/api/Notice/GetMonthlyTicketTrend')
    if (res.data.isSuccess) {
      const data = res.data.data

      if (!data?.this || !data?.last) {
        throw new Error('月数据格式不正确')
      }

      const xAxis = data.this.map(item => {
        const day = Number(item.time).toString().padStart(2, '0')
        return `${day}日`
      })

      // 构建 series 数据 - 月视图显示"本月"和"上月"
      const thisMonth = data.this.map(item => Number(item.count) || 0)
      const lastMonth = data.last.map(item => Number(item.count) || 0)

      monthlyData.value = {
        xAxis: xAxis,
        series: [
          {name: '本月', data: thisMonth, type: 'line'},
          {name: '上月', data: lastMonth, type: 'line'}
        ]
      }
    } else {
      throw new Error(res.data.msg || '获取月曲线数据失败')
    }
  } catch (err) {
    error.value = '获取月曲线数据失败'
    console.error('月数据错误:', err)
  }
}

// 刷新数据方法 - 无感刷新核心
const refreshData = async () => {
  // 保存当前数据用于对比
  const oldDailyData = JSON.stringify(dailyData.value)
  const oldMonthlyData = JSON.stringify(monthlyData.value)

  try {
    // 同时刷新日和月数据
    await Promise.all([fetchDailyData(), fetchMonthlyData()])

    // 对比新旧数据，只有变化时才更新图表
    const newDailyData = JSON.stringify(dailyData.value)
    const newMonthlyData = JSON.stringify(monthlyData.value)

    // 检查数据是否有变化
    const dataChanged = oldDailyData !== newDailyData || oldMonthlyData !== newMonthlyData

    // 数据有变化且当前图表实例存在时才更新
    if (dataChanged && chartInstance) {
      // 使用ECharts的过渡动画更新图表
      chartInstance.setOption(getChartOption(), {
        transition: true,  // 启用过渡动画
        transitionDuration: 500  // 过渡动画持续时间
      })
    }
  } catch (err) {
    console.error('数据刷新失败:', err)
  }
}

// 获取图表配置项
const getChartOption = () => {
  const {xAxis, series} = currentPeriod.value === 'today' ? dailyData.value : monthlyData.value

  // 根据当前周期设置对应的图例名称
  const legendNames = currentPeriod.value === 'today'
      ? ['今日', '昨日']
      : ['本月', '上月']

  if (!xAxis || !series || series.length === 0) {
    console.error('图表数据不完整', {xAxis, series})
    return {}
  }

  // 计算Y轴最大值，确保刻度为整数且有适当余量
  const allData = series.flatMap(item => item.data)
  const maxValue = Math.max(...allData)
  const yAxisMax = maxValue > 0 ? Math.ceil(maxValue * 1.1) : 5  // 至少显示到5，避免数据为0时无刻度

  return {
    tooltip: {trigger: 'axis'},
    legend: {
      data: legendNames,
      top: '5%',
      right: '5%',
      textStyle: {
        color: '#93c5fd'
      }
    },
    xAxis: {
      type: 'category',
      data: xAxis,
      axisLine: {
        lineStyle: {
          color: 'rgba(59, 130, 246, 0.3)'
        }
      },
      axisLabel: {
        color: '#93c5fd'
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: yAxisMax,
      interval: 1,
      axisLabel: {
        color: '#93c5fd',
        formatter: function(value) {
          return Math.round(value);
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(59, 130, 246, 0.3)'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(59, 130, 246, 0.1)'
        }
      },
      boundaryGap: [0, '100%'],
      scale: false
    },
    series: series.map((item, index) => ({
      ...item,
      name: legendNames[index],
      lineStyle: {
        width: 3
      },
      symbol: 'circle',
      symbolSize: 5,
      emphasis: {
        symbolSize: 8
      },
      // 线条平滑过渡
      smooth: true,
      // 区域填充透明度变化
      areaStyle: {
        opacity: 0.1
      }
    }))
  }
}

// 初始化图表
const initChart = () => {
  if (!chart.value) {
    console.error('图表容器不存在')
    return
  }

  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chart.value)
  chartInstance.setOption(getChartOption())
}

// 窗口变化时调整图表大小
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

onMounted(async () => {
  try {
    // 初始加载数据
    await Promise.all([fetchDailyData(), fetchMonthlyData()])
    await nextTick()
    initChart()
  } catch (err) {
    console.error('初始化错误:', err)
    error.value = '图表初始化失败'
  } finally {
    loading.value = false
  }

  // 设置3秒刷新一次数据，实现无感刷新
  refreshInterval = setInterval(refreshData, 3000)

  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  // 清除定时器，防止内存泄漏
  if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }

  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 监听视图切换，更新图表
watch(currentPeriod, () => {
  if (chartInstance) {
    chartInstance.setOption(getChartOption(), {
      transition: true,
      transitionDuration: 500
    })
  }
})
</script>
